<template>
  <header ref="headerRef">
    <div class="logo" @click="router.push('/')">钟伟胜博客</div>
    <nav>
      <a href="javascript:;" @click="router.push('/')">首页</a>
      <a href="javascript:;" @click="toAnchor('about-me')">关于我</a>
      <a href="javascript:;" @click="toAnchor('demo')">Demo</a>
      <a href="javascript:;" @click="toAnchor('article-list')">文章列表</a>
      <a href="javascript:;" @click="toAnchor('footer-menus')">联系方式</a>
    </nav>
    <div class="burger" @click="burgerClick">
      <div class="burger-line1"></div>
      <div class="burger-line2"></div>
      <div class="burger-line3"></div>
    </div>
  </header>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Store, useStore } from "vuex";
export default defineComponent({
  name: "Header",
  setup(props, ctx) {
    const router = useRouter();
    const route = useRoute();
    const headerRef: any = ref(null);
    const store: Store<any> = useStore();
    const storeState = store.state;

    onMounted(() => {
      if (route.path.indexOf("article") !== -1) {
        headerRef.value.className = "sticky";
      }
    });

    watch(
      () => {
        return storeState.scrolled.top;
      },
      (top) => {
        if (top > storeState.viewportSize.height + 100) {
          headerRef.value.className = "sticky";
        } else {
          headerRef.value.className = null;
        }
      }
    );

    const burgerClick = () => {
      headerRef.value.classList.toggle("open");
    };

    const toAnchor = (tar: string): void => {
      ctx.emit("toAnchor", tar);
      if (route.path.indexOf("article") !== -1) {
        localStorage.setItem("anchor", tar);
        router.push("/");
      }
    };
    return {
      headerRef,
      toAnchor,
      router,
      burgerClick,
    };
  },
});
</script>
